package com.szxydb.dmp.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.szxydb.dmp.admin.system.dao.SystemAdminDao;
import com.szxydb.dmp.admin.system.model.SystemAdmin;
import com.szxydb.dmp.admin.system.model.SystemRole;
import com.szxydb.dmp.admin.system.model.TokenModel;
import com.szxydb.dmp.admin.system.request.SystemAdminAddRequest;
import com.szxydb.dmp.admin.system.request.SystemAdminRequest;
import com.szxydb.dmp.admin.system.request.SystemRoleSearchRequest;
import com.szxydb.dmp.admin.system.response.SystemAdminResponse;
import com.szxydb.dmp.admin.system.service.SystemAdminService;
import com.szxydb.dmp.admin.system.service.SystemRoleService;
import com.szxydb.dmp.admin.system.service.TokenManager;
import com.szxydb.dmp.common.PageParamRequest;
import com.szxydb.dmp.exception.CrmebException;
import com.szxydb.dmp.utils.CrmebUtil;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SystemAdminServiceImpl extends ServiceImpl<SystemAdminDao, SystemAdmin> implements SystemAdminService {

    @Resource
    private SystemAdminDao dao;

    @Resource
    private TokenManager tokenManager;

    @Autowired
    private SystemRoleService systemRoleService;

    @Override
    public SystemAdminResponse login(SystemAdminRequest request, String ip) throws Exception {
        LambdaQueryWrapper<SystemAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemAdmin::getAccount,request.getAccount());
        SystemAdmin systemAdmin = dao.selectOne(lambdaQueryWrapper);
        String encryptPassword = CrmebUtil.encryptPassword(request.getPwd(),request.getAccount());
        if (null == systemAdmin){
            throw new CrmebException("用户不存在");
        }

        if (!systemAdmin.getStatus()){
            throw new CrmebException("用户已经被禁用");
        }

        if (systemAdmin.getIsDel()){
            throw new CrmebException("用户已经被删除");
        }

        if (!systemAdmin.getPwd().equals(encryptPassword)){
            throw new CrmebException("账号或者密码不正确");
        }
        TokenModel tokenModel = tokenManager.createToken(systemAdmin.getAccount(),systemAdmin.getId().toString(),TokenModel.TOKEN_REDIS);
        SystemAdminResponse systemAdminResponse = new SystemAdminResponse();
        systemAdminResponse.setToken(tokenModel.getToken());
        BeanUtils.copyProperties(systemAdmin,systemAdminResponse);

        systemAdmin.setLoginCount(systemAdmin.getLoginCount() + 1);
        systemAdmin.setLastIp(ip);
        updateById(systemAdmin);

        return systemAdminResponse;
    }

    @Override
    public SystemAdminResponse getInfo(SystemAdminRequest request) throws Exception {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",request.getId());
        SystemAdmin systemAdmin = dao.selectOne(queryWrapper);
        if (null == systemAdmin || systemAdmin.getId() < 0){
            return null;
        }
        SystemAdminResponse systemAdminResponse = new SystemAdminResponse();
        BeanUtils.copyProperties(systemAdmin,systemAdminResponse);
        return systemAdminResponse;
    }

    @Override
    public List<SystemAdminResponse> getList(SystemAdminRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(),pageParamRequest.getLimit());
        LambdaQueryWrapper<SystemAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        SystemAdmin systemAdmin = new SystemAdmin();
        BeanUtils.copyProperties(request,systemAdmin);
        if (StringUtils.isNotBlank(systemAdmin.getAccount())){
            lambdaQueryWrapper.eq(SystemAdmin::getAccount,systemAdmin.getAccount());
        }
        if (null != systemAdmin.getId()){
            lambdaQueryWrapper.eq(SystemAdmin::getId,systemAdmin.getId());
        }
        if (null != systemAdmin.getIsDel()){
            lambdaQueryWrapper.eq(SystemAdmin::getIsDel,systemAdmin.getIsDel());
        }
        if (StringUtils.isNotBlank(systemAdmin.getLastIp())){
            lambdaQueryWrapper.eq(SystemAdmin::getLastIp,systemAdmin.getLastIp());
        }
        if (null != systemAdmin.getLevel()){
            lambdaQueryWrapper.eq(SystemAdmin::getLevel,systemAdmin.getLevel());
        }
        if (null != systemAdmin.getLoginCount()){
            lambdaQueryWrapper.eq(SystemAdmin::getLoginCount,systemAdmin.getLoginCount());
        }
        if (StringUtils.isNotBlank(systemAdmin.getRealName())){
            lambdaQueryWrapper.like(SystemAdmin::getRealName,systemAdmin.getRealName());
            lambdaQueryWrapper.or().like(SystemAdmin::getAccount,systemAdmin.getRealName());
        }
        if (StringUtils.isNotBlank(systemAdmin.getRoles())){
            lambdaQueryWrapper.eq(SystemAdmin::getRoles,systemAdmin.getRoles());
        }
        if (null != systemAdmin.getStatus()){
            lambdaQueryWrapper.eq(SystemAdmin::getStatus,systemAdmin.getStatus());
        }
        List<SystemAdmin> systemAdmins = dao.selectList(lambdaQueryWrapper);
        List<SystemAdminResponse> systemAdminResponses = new ArrayList<>();
        PageParamRequest pageRole = new PageParamRequest();
        pageRole.setLimit(999);
        List<SystemRole> roleList = systemRoleService.getList(new SystemRoleSearchRequest(),pageRole);
        for (SystemAdmin admin : systemAdmins){
            SystemAdminResponse sar = new SystemAdminResponse();
            BeanUtils.copyProperties(admin,sar);
            sar.setLastTime(admin.getUpdateTime());
            if (StringUtils.isBlank(admin.getRoles())) continue;
            List<Integer> roleIds = CrmebUtil.stringToArrayInt(admin.getRoles());
            List<String> roleNames = new ArrayList<>();
            for (Integer roleId : roleIds) {
                List<SystemRole> hasRoles = roleList.stream().filter(e -> e.getId().equals(roleId)).collect(Collectors.toList());
                if(hasRoles.size()> 0){
                    roleNames.add(hasRoles.stream().map(SystemRole::getRoleName).collect(Collectors.joining(",")));
                }
            }
            sar.setRoleNames(StringUtils.join(roleNames,","));
            systemAdminResponses.add(sar);
        }
        return systemAdminResponses;
    }

    @Override
    public void bind(String wxCode, Integer adminId) {

    }

    @Override
    public SystemAdminResponse getInfoByToken(String token) throws Exception {
        Boolean tokenExsit = tokenManager.checkToken(token,TokenModel.TOKEN_REDIS);
        if (!tokenExsit){
            throw new CrmebException("当前token无效");
        }
        TokenModel tokenModel = tokenManager.getToken(token, TokenModel.TOKEN_REDIS);
        SystemAdminRequest systemAdminRequest = new SystemAdminRequest();
        systemAdminRequest.setId(tokenModel.getUserId());
        return getInfo(systemAdminRequest);
    }

    @Override
    public Boolean logout(String token) throws Exception {
        tokenManager.deleteToken(token,TokenModel.TOKEN_REDIS);
        return true;
    }

    @Override
    public SystemAdminResponse saveAdmin(SystemAdminAddRequest systemAdminAddRequest) throws Exception {
        try {
            Integer result = checkAccount(systemAdminAddRequest.getAccount());
            if (result > 0){
                throw new CrmebException("管理员已存在");
            }
            SystemAdmin systemAdmin = new SystemAdmin();
            BeanUtils.copyProperties(systemAdminAddRequest,systemAdmin);

            String pwd = CrmebUtil.encryptPassword(systemAdmin.getPwd(),systemAdmin.getAccount());
            systemAdminAddRequest.setPwd(pwd);
            SystemAdminResponse systemAdminResponse = new SystemAdminResponse();
            BeanUtils.copyProperties(systemAdminAddRequest,systemAdminResponse);
            if (dao.insert(systemAdmin) <= 0){
                throw new CrmebException("新增管理员失败");
            }
            return systemAdminResponse;
        }catch (Exception e){
            throw new CrmebException("新增管理员异常 "+e.getMessage());
        }
    }

    @Override
    public SystemAdminResponse updateAdmin(SystemAdminRequest systemAdminRequest) throws Exception {
        return null;
    }

    @Override
    public Integer getAdminId() {
        return Integer.parseInt(tokenManager.getLocalInfoException("id"));
    }

    @Override
    public SystemAdmin getInfo(Integer adminId) {
        return getById(adminId);
    }

    @Override
    public SystemAdmin getInfo() {
        return getInfo(getAdminId());
    }

    @Override
    public SystemAdminResponse wechatAuthorizeLogin(String code, String ip) {
        return null;
    }

    @Override
    public Boolean unBind() {
        return null;
    }

    private Integer checkAccount(String account){
        LambdaQueryWrapper<SystemAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemAdmin::getAccount,account);
        return dao.selectCount(lambdaQueryWrapper);
    }
}
